package core;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import application.Application;
import application.Core;

/**
 * This class read from PipedInputStream and write to file.
 * @author Vopalecky
 *
 */
public class PipedOutpuStreamFileWriter extends Application {
	private String fileName;
	private Core core;
	private int id;
	
	/**
	 * Set default values.
	 * @param name
	 * @param core
	 */
	public PipedOutpuStreamFileWriter(String name, Core core){
		fileName = name;
		this.core = core;
	}
	
	/**
	 * Set process id.
	 * @param id
	 */
	public void setID(int id){
		this.id = id;
	}
	
	/**
	 * Reading and writing.
	 */
	@Override
	public void code() {
		File f = new File(fileName);
		try {
			f.createNewFile();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			core.getGui().writeConsole("IOException");
		}
		try {
			FileWriter fw = new FileWriter(f);
			String str = core.read(id);
			while (str != null) {
				fw.write(str + "\n");
				str = core.read(id);				
			}
			core.closeIn(id);
			fw.close();
			core.cleanLastProccess();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			core.getGui().writeConsole("IOException");
		}
		
	}
}
